package com.qbccn.bbs.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.springframework.util.DigestUtils;

/**
 * @author linke
 * @date 2020/5/30 22:44
 * @description
 */
public class CommonUtils {

  /**
   * 获取请求的IP地址
   */
  public static String getIpAddress(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    return ip;
  }

  public static String getNowDateToyyyyMM(){
    SimpleDateFormat format=new SimpleDateFormat("yyyyMM");
    return format.format(new Date());
  }

  public static String getNowDateToyyyyMMdd(){
    SimpleDateFormat format=new SimpleDateFormat("yyyyMMdd");
    return format.format(new Date());
  }

  /**
   * MD5加密
   */
  public static String getMD5(String str){
    return DigestUtils.md5DigestAsHex(str.getBytes());
  }

  /**
   * 验证邮箱是否合法：合法返回true
   */
  public static boolean isEmail(String email) {
    if (email == null)
      return false;
    String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    Pattern p = Pattern.compile(regEx1);
    Matcher m = p.matcher(email);
    if (m.matches())
      return true;
    else
      return false;
  }

  /**
   * 判断是否是由字母、数字、下划线、1~20长度、组成
   */
  public static boolean isPassword(String password) {
    if (password == null)
      return false;
    Pattern p = Pattern.compile("^[0-9a-zA-Z_]{1,20}$");
    if (p.matcher(password).matches())
      return true;
    else
      return false;
  }
}
